import { userInfoData } from '@/type.d';
import { defineStore } from 'pinia';
import type { RouteRecordRaw } from 'vue-router';
import { SET_SETTING_System_Icon, SET_SETTING_System_Title } from '@/utils/common';
import store from '@/store';
import { Storage } from '@/utils/Storage';
// import { generatorDynamicRouter } from '@/router/generator-router';
import { resetRouter } from '@/router';
import request from '@/api/index'
interface UserState {
  userInfo: {
    token: string;
    siteName: string;
    userId: number;
    userName: string,
    siteId: number;
    orgId: number;
    menues: RouteRecordRaw[];
    [propName: string]: any

  }
}

export const useUserStore = defineStore({
  id: 'user',
  persist: {
    enabled: true,//开启数据持久化
    strategies: [
      {
        key: 'user',//给一个要保存的名称
        storage: sessionStorage,//sessionStorage / localStorage 存储方式
      }
    ]
  },
  state: (): UserState => ({
    userInfo: {
      token: Storage.get('ACCESS_TOKEN', null),
      siteName: 'amdin',
      menues: [],
      userId: 0,
      userName: '',
      siteId: 0,
      orgId: 0,
    },
  }),
  actions: {
    /** 清空token及用户信息 */
    resetToken() {
      this.userInfo = {
        token: '',
        siteName: 'amdin',
        menues: [],
        userId: 0,
        userName: '',
        siteId: 0,
        orgId: 0,
      }
      Storage.remove('ACCESS_TOKEN')
    },
    /** 登录成功保存token */
    setUser(state: any) {
      this.userInfo = {

        ...state
      }
      const ex = 7 * 24 * 60 * 60 * 1000;
      SET_SETTING_System_Icon(this.userInfo?.tabPic);
      SET_SETTING_System_Title(this.userInfo.pageTitleSetting);
      Storage.set('ACCESS_TOKEN', this.userInfo.token, ex);
      return this.userInfo
    },

    /** 登录成功之后, 获取用户信息以及生成权限路由 */

    /** 登出 */
    async logout() {
      await request.fetchLogout({ token: this.userInfo.token });
      this.resetToken();
      // resetRouter();
    },
  },
});

// 在组件setup函数外使用
export function useUserStoreWithOut() {
  return useUserStore(store);
}
